package com.lottery.shadowbd.io.api;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lottery.shadowbd.callback.Callback;
import com.lottery.shadowbd.callback.ECallback;
import com.lottery.shadowbd.callback.OnDownloadListener;
import com.lottery.shadowbd.io.http.OkHttpIO;
import com.lottery.shadowbd.tuple.Tuple2;
import com.lottery.shadowbd.utils.LogUtils;

import java.io.InputStream;

import okhttp3.FormBody;
import okhttp3.MultipartBody;

/**
 * Created by Administrator on 2017/5/19 0019.
 */
public class MainApiIO {

    volatile static MainApiIO instance;

    public MainApiIO() {

    }

    static public MainApiIO getInstance() {
        if (instance == null) {
            synchronized (MainApiIO.class) {
                if (instance == null) {
                    instance = new MainApiIO();
                }
            }
        }

        return instance;
    }

    /**
     * 异步POST接口
     *
     * @param url         短地址
     * @param requestBody 请求参数
     * @param callback    回调
     */
    public void postRequest(@NonNull String url, @Nullable FormBody requestBody, @Nullable final ECallback<String, Tuple2<Integer, String>> callback) {
        if (requestBody != null) {
            int len = requestBody.size();
            String params = "";
            for (int i = 0; i < len; i++) {
                params += (requestBody.encodedName(i) + "=" + requestBody.encodedValue(i) + "; ");
            }
            LogUtils.d("--->params: " + params);
        }
        LogUtils.d("--->url: " + url);
        OkHttpIO.getInstance().post(url, requestBody, new Callback<Tuple2<Integer, String>, Exception>() {
            @Override
            public void onSuccess(Tuple2<Integer, String> res) {
                try {
                    if (res._1 == 200) {
                        LogUtils.e("res._2==" + res._2);
                        JSONObject jsonObject = JSON.parseObject(res._2);

                        int status = jsonObject.getInteger("status");

                        if(status == 1) {
                            callback.onSuccess(res._2);
                        } else {
                            callback.onError(new Tuple2<Integer, String>(status, jsonObject.getString("desc")));
                        }
                    } else {
                        throw new RuntimeException(String.format("HTTP CODE : %d", res._1));
                    }
                } catch (Exception e) {
                    LogUtils.e("--->MainApiIo error: " + e.getMessage());
                    if (callback != null) {
                        callback.onThrowable(e);
                    }
                }
            }

            @Override
            public void onError(Exception error) {
                LogUtils.e("--->error: " + error.getMessage() + "  " + error);
                if (callback != null) {
                    callback.onThrowable(error);
                }
            }
        });
    }

    /**
     * 异步POST接口
     *
     * @param url         短地址
     * @param requestBody 请求参数
     * @param callback    回调
     */
    public void postLotRequest(@NonNull String url, @Nullable FormBody requestBody, @Nullable final ECallback<String, Tuple2<Integer, String>> callback) {
        if (requestBody != null) {
            int len = requestBody.size();
            String params = "";
            for (int i = 0; i < len; i++) {
                params += (requestBody.encodedName(i) + "=" + requestBody.encodedValue(i) + "; ");
            }
            LogUtils.d("--->params: " + params);
        }
        LogUtils.d("--->url: " + url);
        OkHttpIO.getInstance().post(url, requestBody, new Callback<Tuple2<Integer, String>, Exception>() {
            @Override
            public void onSuccess(Tuple2<Integer, String> res) {
                try {
                    if (res._1 == 200) {
                        LogUtils.e("res._2==" + res._2);
                        JSONObject jsonObject = JSON.parseObject(res._2);

                        callback.onSuccess(res._2);

                    } else {
                        throw new RuntimeException(String.format("HTTP CODE : %d", res._1));
                    }
                } catch (Exception e) {
                    LogUtils.e("--->MainApiIo error: " + e.getMessage());
                    if (callback != null) {
                        callback.onThrowable(e);
                    }
                }
            }

            @Override
            public void onError(Exception error) {
                LogUtils.e("--->error: " + error.getMessage() + "  " + error);
                if (callback != null) {
                    callback.onThrowable(error);
                }
            }
        });
    }

    /**
     * 异步POST接口
     *
     * @param url         短地址
     * @param callback    回调
     */
    public void postAsnyRequest(@NonNull String url, @Nullable final ECallback<InputStream, Tuple2<Integer, InputStream>> callback) {

        LogUtils.d("--->url: " + url);
        OkHttpIO.getInstance().getTrendAsny(url, new Callback<Tuple2<Integer, InputStream>, Exception>() {
            @Override
            public void onSuccess(Tuple2<Integer, InputStream> res) {
                try {
                    if (res._1 == 200) {
                        LogUtils.e("res._2==" + res._2);
                        callback.onSuccess(res._2);

                    } else {
                        throw new RuntimeException(String.format("HTTP CODE : %d", res._1));
                    }
                } catch (Exception e) {
                    LogUtils.e("--->MainApiIo error: " + e.getMessage());
                    if (callback != null) {
                        callback.onThrowable(e);
                    }
                }
            }

            @Override
            public void onError(Exception error) {
                LogUtils.e("--->error: " + error.getMessage() + "  " + error);
                if (callback != null) {
                    callback.onThrowable(error);
                }
            }
        });
    }

    /**
     * 异步下载文件接口
     *
     * @param url              短地址
     * @param savePath         文件保存路径
     * @param saveName         文件保存名
     * @param downloadListener 回调
     */
    public void postDownLoad(@NonNull String url, @NonNull final String savePath, @NonNull final String saveName, @Nullable final OnDownloadListener downloadListener) {
        LogUtils.d("--->url: " + url);
        OkHttpIO.getInstance().postDownload(url, savePath, saveName, new OnDownloadListener() {
            @Override
            public void onDownloadSuccess() {
                if (downloadListener != null) {
                    downloadListener.onDownloadSuccess();
                }
            }

            @Override
            public void onDownloading(long total, long current) {
                if (downloadListener != null) {
                    downloadListener.onDownloading(total, current);
                }
            }

            @Override
            public void onDownloadFailed(Exception e) {
                if (downloadListener != null) {
                    downloadListener.onDownloadFailed(e);
                }
            }
        });
    }
}
